package com.icebergteam.warfacewidget.news.ui;

import java.util.ArrayList;
import java.util.Locale;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.text.Html;
import android.view.View;
import android.widget.RemoteViews;
import com.icebergteam.warfacewidget.AppManager;
import com.icebergteam.warfacewidget.R;
import com.icebergteam.warfacewidget.core.ListViewFactory;
import com.icebergteam.warfacewidget.core.LogManager;
import com.icebergteam.warfacewidget.core.NotificationMessage;
import com.icebergteam.warfacewidget.core.NotificationService;
import com.icebergteam.warfacewidget.core.Parser;
import com.icebergteam.warfacewidget.core.utils.TimeDateUtils;
import com.icebergteam.warfacewidget.core.utils.ViewUtils;
import com.icebergteam.warfacewidget.data.sql.NewsTable;
import com.icebergteam.warfacewidget.news.data.NewsItem;


public class NewsListViewFactory extends ListViewFactory {
	public static String className = NewsListViewFactory.class
			.getCanonicalName();

	private ArrayList<NewsItem> listRSSItems = new ArrayList<NewsItem>();

	public NewsListViewFactory(Context ctxt, Intent intent) {
		super(ctxt, intent);
		try {
			
			Cursor cursor = AppManager.getDatabase().getNewsTable().getNews(AppManager.getNewsSettings().getCategories());
			
			int number = 0;
			String bigContentText = "";
			
			boolean checkRestore = intent.getExtras() != null && intent.getExtras().getBoolean(Parser.KEY_INTENT_RESTORE) == false;
			
			int firstUnreadedItemIndex = -1;
				
			while(cursor!= null && cursor.moveToNext()){
				NewsItem item = new NewsItem();
				item.setTitle(cursor.getString(cursor.getColumnIndex(NewsTable.FIELD_TITLE.trim())));
				item.setPubdate(cursor.getLong(cursor.getColumnIndex(NewsTable.FIELD_PUBDATE.trim())));
				item.setRead(cursor.getInt(cursor.getColumnIndex(NewsTable.FIELD_READ.trim())));
				listRSSItems.add(item);
				
				if(checkRestore && !item.isRead()){
					number ++;
					bigContentText += item.getTitle() + "\n";
					if(firstUnreadedItemIndex < 0){
						firstUnreadedItemIndex = listRSSItems.size() -1;
					}
				}
			}
			
			count = cursor.getCount();
			cursor.close();
			if(checkRestore && !bigContentText.isEmpty()){
				NotificationMessage message = new NotificationMessage();
				message.setNumber(number);
				message.setBigContentText((firstUnreadedItemIndex < firstUnreadedItemIndex + number -1 ) ? bigContentText: null);
				message.setSmallContentText(listRSSItems.get(firstUnreadedItemIndex).getTitle());
				message.setFirstUnreadedItemIndex(firstUnreadedItemIndex);
				message.setTitle(String.format("%s %s", AppManager.getContext().getResources().getString(R.string.project_name), AppManager.getContext().getResources().getString(R.string.news_activity_title)));
				message.setTickerTitle(String.format("%s (%s)\n%s", message.getTitle(), number, message.getSmallContentText()));
				message.setSmallIcon(BitmapFactory.decodeResource(AppManager.getContext().getResources(), R.drawable.widget_service_news_icon));
				
				Intent notifyIntent = new Intent(AppManager.getContext(),
						NewsActivity.class);

				notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
						| Intent.FLAG_ACTIVITY_CLEAR_TASK);
				notifyIntent.putExtra(NewsListViewFactory.POS_INTENT_KEY,
						message.getFirstUnreadedItemIndex());
				notifyIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1));
				PendingIntent pendingIntent = PendingIntent.getActivity(AppManager.getContext(), 0,
						notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
				
				message.setIntent(pendingIntent);
				
				Intent intentNotif = new Intent(intent);
				intentNotif.setClass(AppManager.getContext(), NotificationService.class);
				intentNotif.putExtra(NotificationService.KEY_NOTIF_MESSAGE, message);
					
				AppManager.getContext().startService(intentNotif);
			}
			
			
			LogManager.LogV(NewsListViewFactory.className,LogManager.getExecuteMethodName(),
							((cursor == null) ? cursor == null
									: cursor.toString()),
							((ctxt == null) ? ctxt == null : ctxt.toString()), count);
		
		} catch (Exception e) {
			LogManager.LogEA(className, ViewUtils.getErrorMessage(e));
		} 

	}

	@Override
	public RemoteViews getViewAt(int position) {
		try {
			RemoteViews row = new RemoteViews(context.getPackageName(),
					R.layout.news_list_item_widget_layout);
	
			LogManager.LogV(className, LogManager.getExecuteMethodName(), position, count);
			
			NewsItem RSSItem = listRSSItems.get(position);
			
			if(RSSItem != null){
				row.setTextViewText(R.id.news_list_item_widget_layout_title_textview,
						Html.fromHtml(RSSItem.getTitle()));
				
				
					row.setTextViewText(R.id.news_list_item_widget_layout_date,
								Html.fromHtml(TimeDateUtils.getDateStringFromNormalTimestamp(RSSItem.getPubdate(),  "dd MMM yyyy HH:mm:ss", new Locale(AppManager.getLocaleManager().getCurrentServerLang()))));
			
			
				row.setViewVisibility(R.id.news_list_item_widget_layout_newsicon_imageview, (RSSItem.isRead()) ? View.GONE: View.VISIBLE);
				
					
				Intent i = new Intent();
				i.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1));
				i.putExtra(NewsListViewFactory.POS_INTENT_KEY, (position));
				row.setOnClickFillInIntent(R.id.news_list_item_widget_layout, i);
			
				
			}
			return row;
		} catch (NumberFormatException e) {
			LogManager.LogEA(className, ViewUtils.getErrorMessage(e));
		} catch (Exception e) {
			LogManager.LogEA(className, ViewUtils.getErrorMessage(e));
		}
		return null;
	}
}